<script setup>
import menuTree from "./views/components/menuTree.vue";
import controlBar from "./views/components/controlBar.vue";
import helpBar from "./views/components/helpBar.vue";
import { RouterView, useRoute, useRouter } from "vue-router";
import { useCounterStore } from "@/stores/counter";
import { storeToRefs } from "pinia";
import { levels, colors } from "./app";
import { onMounted, ref, onUnmounted, watch } from "vue";
import { getMaterialList, getDataList, getInfo } from "@/api/2d";

import { ArrowLeft } from "@element-plus/icons-vue";
import { v4 as uuid } from "uuid";
const store = useCounterStore();
const route = useRoute();
const router = useRouter();

const {
  color,
  level,
  menuTreeList,
  list,
  createTime,
  dataList,
  noOperationNum,
  workPackId,
  sign,
  processTypeName,
  workUserName,
  taskName,
  receiveTime,
  workUserDomain,
  rollbackKeys,
} = storeToRefs(store);

onUnmounted(() => {
  clearTimeout(timer); // 清除计时器
  removeListeners(); // 移除监听器
});
// if (route.query.workPackId) {
//   alert(route.query.workPackId);
//   workPackId.value = route.query.workPackId;
//   sign.value = route.query.sign;
// }

onMounted(async () => {
  startTimer(); // 页面加载后立即开始计时
  listenToUserActivity();
  createTime.value = new Date();
  list.value = [];
  const query = window.location.search;
  if (query) {
    workPackId.value = query.match(/=([^&]*)/)[1];
    sign.value = query.match(/^[^=]*=[^=]*=(.*)/)[1];
  }
  await getInfo({ workPackId: workPackId.value, sign: sign.value }).then(
    (res) => {
      processTypeName.value = res.data.data?.processTypeName;
      workUserName.value = res.data.data?.workUserName;
      taskName.value = res.data.data?.taskName;
      receiveTime.value = res.data.data?.createTime;
      workUserDomain.value = res.data.data?.workUserDomain;
    }
  );

  // 获取参数值
  await getMaterialList({
    workPackId: workPackId.value,
    sign: sign.value,
  }).then((res) => {
    menuTreeList.value = [];
    if (res.data.data) {
      rollbackKeys.value = res.data.data?.labelKeys;
      let treeList = [JSON.parse(res.data.data?.configContent).topic];
      treeList[0].topics[0].topics.forEach((i) => {
        if (rollbackKeys.value.includes(i.title.match(/#(.*?)=/)[1])) {
          menuTreeList.value.push(i);
        }
      });
    }

    let materialList = res.data.data?.materialList;
    getDataList({
      workPackId: workPackId.value,
      sign: sign.value,
    }).then((res) => {
      dataList.value = res.data.data?.dataList;
      res.data?.data?.dataList.forEach((i) => {
        let materialId = i.materialId;
        let filePath = "";
        materialList.forEach((id) => {
          if (id.materialId == materialId) {
            filePath = id.filePath;
          }
        });
        let reactLists = [
          "rect",
          "line",
          "point",
          "polygon",
          "rect_line_combination",
        ];
        i.details.forEach((item) => {
          let labelList = [];
          let valueList = [];
          if (item.labelKey.slice(0, 5) == "shape") {
            const index = item.labelKey.indexOf(":");
            if (reactLists.includes(item.labelKey.substring(index + 1))) {
              // 查找 i.details 中所有具有相同 markId 的项
              i.details.forEach((detail) => {
                if (detail.labelKey.slice(0, 5) != "shape") {
                  if (detail.markId === item.markId && detail !== item) {
                    // 确保不重复添加自身
                    labelList.push(detail.labelKey);
                    valueList.push(detail.labelValue);
                  }
                }
              });
              list.value.push({
                labelList,
                valueList,
                filePath,
                level: 1,
                materialId: i.materialId,
                borderColor: "red",
                url: "https://img3.huamaocdn.com/upload/bizhi/images/1000w680h/2022/06/202206231433395690.jpg",
                marks: [
                  {
                    shape_type: item.labelKey.substring(index + 1),
                    value: item.labelValue,
                  },
                ],
                ...item,
                id: uuid(),
              });

              console.log("list.value", list.value);
            }
          }
        });
      });
    });
  });
});
const component = ref(null);

const change = () => {
  if (route.name == "main") {
    component.value.changePage();
  } else {
    component.value.clear();
  }
};

const timeout = 20 * 60 * 1000; // 1分钟
let timer = null;

// 重置计时器的方法
const resetTimer = () => {
  clearTimeout(timer);
  startTimer();
};

// 开始计时器
const startTimer = () => {
  timer = setTimeout(() => {
    noOperationNum.value += 1;
    // 可在此处添加其他处理逻辑，比如发送通知或执行特定操作
  }, timeout);
};

// 监听事件
const listenToUserActivity = () => {
  window.addEventListener("mousemove", resetTimer);
  window.addEventListener("mousedown", resetTimer);
  window.addEventListener("keypress", resetTimer);
  window.addEventListener("DOMMouseScroll", resetTimer);
  window.addEventListener("mousewheel", resetTimer);
  window.addEventListener("touchmove", resetTimer);
  window.addEventListener("keydown", resetTimer);
};

// 移除监听器
const removeListeners = () => {
  window.removeEventListener("mousemove", resetTimer);
  window.removeEventListener("mousedown", resetTimer);
  window.removeEventListener("keypress", resetTimer);
  window.removeEventListener("DOMMouseScroll", resetTimer);
  window.removeEventListener("mousewheel", resetTimer);
  window.removeEventListener("touchmove", resetTimer);
  window.removeEventListener("keydown", resetTimer);
};
</script>

<template>
  <helpBar />
  <div class="body">
    <div class="left">
      <menuTree @change="change" /><controlBar @change="change" />
    </div>
    <div class="right">
      <div class="title">
        <div>
          <!-- {{ img }} -->
          <el-button
            type="text"
            v-if="route.name == 'main'"
            :icon="ArrowLeft"
            @click="router.go(-1)"
            >返回主页</el-button
          >

          <span class="ml-10 c-red font-14 font-bold">工作包内容</span>
          <span class="ml-10 c-yellow font-14 font-bold"
            >项目名称:{{ taskName }}</span
          >
          <span class="ml-10 c-yellow font-14 font-bold"
            >工序名称:{{ processTypeName }}</span
          >
          <span class="ml-10 c-yellow font-14 font-bold"
            >标注人员名称:{{ workUserName }}</span
          >
          <!-- <span class="ml-10 c-yellow font-14 font-bold"
            >创建时间:{{ receiveTime }}</span
          > -->
        </div>
        <!-- v-if="route.name == 'scroll'" -->
        <div>
          <el-select
            v-model="color"
            placeholder="所选标签"
            style="width: 120px; margin-right: 5px"
            clearable
            @change="change"
          >
            <el-option
              v-for="item in colors"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            clearable
            @change="change"
            v-model="level"
            placeholder="所选评级"
            style="width: 120px"
          >
            <el-option
              v-for="item in levels"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>
      <KeepAlive>
        <RouterView v-slot="{ Component }">
          <component ref="component" :is="Component"></component>
        </RouterView>
      </KeepAlive>
    </div>
  </div>
</template>

<style scoped lang="scss">
.menu {
  width: 100%;
}
.body {
  width: 100%;
  display: flex;
  .left {
    width: 320px;
  }
  .right {
    margin-left: 5px;
    flex: 1;
    box-sizing: border-box;

    .title {
      width: 100%;
      height: 40px;
      padding: 5px 10px;
      display: flex;
      justify-content: space-between;
      box-sizing: border-box;
      background-color: #383838;
    }
  }
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>
